package com.atguigu.tingshu.user.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.atguigu.tingshu.user.config.properties.WxAutoProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;

/**
 * Author:huzhongkui
 * Date: 2025-03-11 星期二 10:44:21
 * Description:
 */

@Configuration   // 微信的自动配置类
@EnableConfigurationProperties(WxAutoProperties.class)
public class WxAppAutoConfiguration {


    @Autowired
    WxAutoProperties wxAutoProperties;

    /**
     * 定义WxMaService的Bean对象
     */
    @Bean
    public WxMaService wxMaService() {
        // 1.创建WxMaService接口的对象出来
        WxMaService wxMaService = new WxMaServiceImpl();
        // 2.创建一个微信配置对象
        WxMaDefaultConfigImpl wxMaDefaultConfig = new WxMaDefaultConfigImpl();
        wxMaDefaultConfig.setAppid(wxAutoProperties.getAppId());
        wxMaDefaultConfig.setSecret(wxAutoProperties.getAppSecret());
        // 3.将配置对象放到WxMaService对象中
        wxMaService.setWxMaConfig(wxMaDefaultConfig);

        return wxMaService;
    }


    // 定义RSA签名的Bean对象
    @Bean
    public RsaSigner rsaSigner() {
        // 1.读取这个证书
        ClassPathResource classPathResource = new ClassPathResource("tingshu.jks");

        // 2.创建一个工厂对象
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "tingshu".toCharArray());


        // 3.从工厂中获取钥匙对象（公钥和私钥）
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("tingshu", "tingshu".toCharArray());

        // 4.获取私钥
        //  RSA:非对称加密的方式（公钥（加密和验签）和私钥：解密（加签：防止数据被篡改））   对称加密(一把钥匙)
        //  加签：为了防止数据被篡改
        //  加密：将数据转成密文（password=11111 axbfcdxd） 对敏感数据做保护的
        RSAPrivateKey aPrivate = (RSAPrivateKey) keyPair.getPrivate();

        RsaSigner rsaSigner = new RsaSigner(aPrivate);

        return rsaSigner;
    }


}
